﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using QASampling.WSStellent;
using System.Configuration;

namespace QASampling.BusinessObject
{
    public class MIIWebservice : WSStellent.GetFile
    {
        protected override System.Net.WebRequest GetWebRequest(Uri uri)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);

            if (PreAuthenticate)
            {
                NetworkCredential networkCredentials = Credentials.GetCredential(uri, "Basic");

                if (networkCredentials != null)
                {
                    byte[] credentialBuffer = new UTF8Encoding().GetBytes(
                      networkCredentials.UserName + ":" +
                      networkCredentials.Password);
                    request.Headers["Authorization"] =
                      "Basic " + Convert.ToBase64String(credentialBuffer);
                }
                else
                {
                    throw new ApplicationException("No network credentials");
                }
            }
            return request;
        }

        internal Stream GetFile(int ID)
        {
            Stream stream = null;
            try
            {
                string wsUrl = ConfigurationManager.AppSettings["webserviceUrl"];
                string httpUsername = ConfigurationManager.AppSettings["httpUsername"];
                string httpPassword = ConfigurationManager.AppSettings["httpPassword"];

                MIIWebservice ws = new MIIWebservice();
                ws.Url = wsUrl;
                NetworkCredential netCredential = new NetworkCredential(httpUsername, httpPassword);
                Uri uri = new Uri(ws.Url);
                ICredentials credentials = netCredential.GetCredential(uri, "Basic");
                ws.Credentials = credentials;
                ws.PreAuthenticate = true;

                IdcProperty[] prop = new IdcProperty[1];
                for (int i = 0; i < prop.Length; i++)
                    prop[i] = new IdcProperty();

                prop[0].name = "xNPWP";
                prop[0].value = "240433763024000";

                WSStellent.GetFileByIDResult rs = ws.GetFileByID(ID, true, "Primary", prop);
                stream = new MemoryStream(rs.downloadFile.fileContent);
                return stream;

            }
            catch (Exception ex)
            {
                return stream;
            }

        }
    }
}
